<template>
  <div class="wrap">
    <div class="wrap-button">
      <a-button style="margin-right: 8px" type="primary" @click="showAddRole">新增</a-button>
      <a-button type="primary" style="margin-right: 8px; float: right" @click="list">查询</a-button>
      <a-input
        v-model:value="deviceSO.keyword"
        style="width: 180px; margin-right: 8px; float: right"
        placeholder="输入关键字查询"
        allow-clear
      >
        <template #prefix>
          <user-outlined />
        </template>
      </a-input>
      <a-select
        v-if="isSuperAdmin"
        placeholder="选择租户"
        v-model:value="deviceSO.tenantId"
        style="width: 180px; margin-right: 8px; float: right"
        allowClear
        @change="handleChangeTenant"
      >
        <a-select-option v-for="item in tenants" :key="item.id" :value="item.id">{{
          item.name
        }}</a-select-option>
      </a-select>

      <!-- <div style="float: right">
        <a-input
          v-model:value="keyword"
          style="width: 180px; margin-right: 8px"
          placeholder="输入关键字查询"
        >
          <template #prefix>
            <user-outlined />
          </template>
        </a-input>
        <a-button type="primary" @click="handleSearch">查询</a-button>
      </div> -->
    </div>
    <div style="flex: 1">
      <a-spin :spinning="loading">
        <div
          v-for="device in devices"
          :key="device.id"
          style="width: 240px; display: inline-block; margin-top: 16px; margin-right: 24px"
        >
          <a-badge-ribbon :text="transformWorkStatus(device.pileStatus)">
            <a-card
              hoverable
              style="width: 240px"
              @click="showDetail(device.code, device.machCode)"
            >
              <template #cover>
                <img
                  style="width: 240px; height: 260px; object-fit: cover"
                  alt="example"
                  src="../.././assets/images/微信图片_20240801103113.png"
                />
              </template>
              <a-card-meta :title="device.name ? device.name : device.code">
                <template #description
                  ><div
                    ><span>设备编码：</span><span>{{ device.code }}</span></div
                  ><div
                    ><span>机器编号：</span><span>{{ device.machCode }}</span></div
                  >
                </template>
              </a-card-meta>
            </a-card>
          </a-badge-ribbon>
        </div>
      </a-spin>
      <!-- <div style="width: 240px; display: inline-block; margin-top: 16px; margin-right: 24px">
        <a-badge-ribbon text="运行中">
          <a-card hoverable style="width: 240px" @click="showDetail('MX0124030001')">
            <template #cover>
              <img
                style="width: 240px; height: 160px; object-fit: cover"
                alt="example"
                src="https://os.alipayobjects.com/rmsportal/QBnOOoLaAfKPirc.png"
              />
            </template>
            <a-card-meta title="搅拌桩1号">
              <template #description
                ><div><span>设备编码</span><span>MX0124030001</span></div
                ><div><span>机器编号</span><span>123</span></div>
              </template>
            </a-card-meta>
          </a-card>
        </a-badge-ribbon>
      </div>
      <div style="width: 240px; display: inline-block; margin-top: 16px; margin-right: 24px">
        <a-badge-ribbon text="运行中">
          <a-card hoverable style="width: 240px">
            <template #cover>
              <img
                style="width: 240px; height: 160px; object-fit: cover"
                alt="example"
                src="https://os.alipayobjects.com/rmsportal/QBnOOoLaAfKPirc.png"
              />
            </template>
            <a-card-meta title="搅拌桩1号">
              <template #description
                ><div><span>设备编码</span><span>MX0124030001</span></div
                ><div><span>机器编号</span><span>123</span></div>
              </template>
            </a-card-meta>
          </a-card>
        </a-badge-ribbon>
      </div> -->
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { h, ref, onMounted, reactive, watch, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import {
    DeleteOutlined,
    SettingOutlined,
    EditOutlined,
    EllipsisOutlined,
  } from '@ant-design/icons-vue'
  import { FormInstance, message } from 'ant-design-vue'
  import type { TreeProps } from 'ant-design-vue'
  // import { BaseTitle } from '/@/components/Title'
  import { listRole, addRole, deleteRole, listPermission, setPermission } from '/@/api/sys/role'
  import { RoleInfo, RolePermissionModel } from '/@/api/sys/model/roleModel'
  import type { AppRouteRecordRaw } from '/@/router/types'
  import { getMenuList } from '/@/api/sys/menu'
  import { listTenant } from '/@/api/sys/tenant'
  import { TenantModel } from '/@/api/sys/model/tenantModel'
  import { Modal } from 'ant-design-vue'
  import { listDevice } from '/@/api/pd/device'
  import { DeviceListResult, DeviceListSO } from '/@/api/pd/model/deviceModel'
  import { useUserStore } from '/@/store/modules/user'

  const open = ref<boolean>(false)
  const openPermission = ref<boolean>(false)
  const loading = ref(false)
  const router = useRouter()
  const devices = ref<DeviceListResult[]>([])
  const tenants = ref<TenantModel[]>([])
  const userStore = useUserStore()
  const isSuperAdmin = userStore.getSuperAdmin
  const columns = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
      align: 'center',
    },
    {
      title: '角色编码',
      dataIndex: 'roleCode',
      key: 'roleCode',
      align: 'center',
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      align: 'center',
      width: 240,
    },
  ]

  let data = ref<RoleInfo[]>([])

  let routeList: AppRouteRecordRaw[] = []

  let checkedKeys = ref<string[]>(['3'])

  const fieldNames: TreeProps['fieldNames'] = {
    key: 'id',
    title: 'name',
  }

  const deviceSO = computed(() => ({
    tenantId: undefined,
    projectId: undefined,
    keyword: undefined,
  }))

  let currRoleId = ref<string>('')

  watch(checkedKeys, () => {
    console.log('checkedKeys', checkedKeys)
  })
  //#endregion

  onMounted(() => {
    if (isSuperAdmin) initTenant()
    list()
  })

  async function list() {
    loading.value = true

    devices.value = await listDevice(deviceSO.value)
    loading.value = false
  }

  function initTenant() {
    listTenant().then((res) => {
      tenants.value = res
    })
  }

  function handleTableChange() {}

  //#region 用户

  const formRef = ref<FormInstance>()

  let formState = reactive<RoleInfo>({
    id: '',
    roleName: '',
    roleCode: '',
  })

  const showAddRole = () => {
    open.value = true
    formRef.value?.resetFields()
  }

  const handleAddSubmit = () => {
    formRef.value
      ?.validateFields()
      .then(() => {
        addRole(formState).then(() => {
          message.success('新增成功')
          open.value = false
          list()
        })
      })
      .catch(() => {
        message.error('表单填写错误')
      })
  }

  const handleDelete = (record) => {
    Modal.confirm({
      title: '提示',
      maskClosable: true,
      content: '确定要删除该角色吗？',
      onOk() {
        deleteRole(record.id).then(() => {
          list()
          message.success('删除成功')
        })
      },
      onCancel() {},
    })
  }

  //
  const showPermission = async (record) => {
    routeList = (await getMenuList()) as AppRouteRecordRaw[]
    console.log('routeList', routeList)
    checkedKeys.value = await listPermission(record.id)
    currRoleId.value = record.id
    openPermission.value = true
  }

  const handlePermissionSubmit = async () => {
    console.log(checkedKeys.value)
    const params: RolePermissionModel = {
      roleId: currRoleId.value,
      menus: checkedKeys.value,
    }
    await setPermission(params)
    message.success('设置成功')
    openPermission.value = false
  }

  const showDetail = (deviceCode, machCode) => {
    console.log(deviceCode)
    router.push({ path: '/device/detail', query: { deviceCode, machCode } })
  }

  const transformWorkStatus = (status) => {
    switch (status) {
      case 1:
        return '停钻'
      case 2:
        return '下钻'
      case 3:
        return '提钻'
      case 4:
        return '复下'
      case 5:
        return '复提'
      case 6:
        return '喷浆'
      default:
        return '未知'
    }
  }

  const handleChangeTenant = () => {
    list()
  }

  //#endregion
</script>

<style lang="scss" scoped>
  .wrap {
    display: flex;
    flex-direction: column;
    flex: 1;
    &-table {
      margin-top: 16px;
    }
  }
</style>
